//
//  mm_repairItemModifyViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-7-20.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "mm_repairItemModifyViewController.h"
#import "MyAFNetWorkManager.h"
#import "SVProgressHUD.h"

@interface mm_repairItemModifyViewController ()

@property (strong, nonatomic) IBOutlet UITextField *repairCode;
@property (weak, nonatomic) IBOutlet UITextField *repairNameTxt;

@property (strong, nonatomic) IBOutlet UITextField *standardWorkHourTxt;
@property (strong, nonatomic) IBOutlet UITextField *workHourCharge;

@property (strong, nonatomic) IBOutlet UIButton *chargeDiffBtn;

/** 收费区分列表 */
@property(nonatomic,strong)NSMutableDictionary *chargeDiff;
@property(nonatomic,strong)NSMutableArray *chargeDiffKeys;
@property(nonatomic,strong)NSMutableDictionary *chargeDiffValKey;

/** 维修分类 */
@property (weak, nonatomic) IBOutlet UIButton *repairTypeBtn;
@property(nonatomic,strong)NSMutableArray *repairTypeNames;
@property(nonatomic,strong)NSMutableDictionary *repairTypeDic;
@property(nonatomic,strong)NSMutableDictionary *repairTypeCodeDic;

/** 工时单价 */
@property(nonatomic,strong)NSMutableArray *labourPrices;
@property(nonatomic,weak)IBOutlet UIButton *labourPriceBtn;

@end

@implementation mm_repairItemModifyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.frame = CGRectMake(0, 0, 500, 600);

    //初始化数据
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSDictionary *dicTmp = modelIns.repairProjects[modelIns.nRowForRepairItemList];
    self.repairCode.text = dicTmp[@"LABOUR_CODE"];
    if ([dicTmp[@"LABOUR_CODE"] containsString:@"LSDY"]) {
        self.repairNameTxt.enabled = YES;
        self.repairNameTxt.backgroundColor = [UIColor whiteColor];
    }
    self.repairNameTxt.text = dicTmp[@"LABOUR_NAME"];
    self.repairNameTxt.delegate = self;
    self.standardWorkHourTxt.text = [self getTextWithValue:dicTmp[@"STD_LABOUR_HOUR"]];
    [self.labourPriceBtn setTitle:[NSString stringWithFormat:@"%.2f",[dicTmp[@"LABOUR_PRICE"] doubleValue]] forState:UIControlStateNormal];
    self.workHourCharge.text = [self getTextWithValue:dicTmp[@"LABOUR_AMOUNT"]];
    [self chargeDiffKeys];
    NSString *code = dicTmp[@"CHARGE_PARTITION_CODE"];
    [self.chargeDiffBtn setTitle:self.chargeDiffValKey[code] forState:UIControlStateNormal];
    [self repairTypeNames];
    [self.repairTypeBtn setTitle:self.repairTypeCodeDic[dicTmp[@"REPAIR_TYPE_CODE"]] forState:UIControlStateNormal];
    
    if ([code isEqualToString:@"S002"]||[code isEqualToString:@"S004"]||[code isEqualToString:@"S008"]||[code isEqualToString:@"S009"]||[code isEqualToString:@"S010"]) {
        self.labourPriceBtn.enabled = NO;
    }
    
    [self registerNotificationForKeyBoard];
}

-(NSString *)getTextWithValue:(id)value{
    NSString *text = nil;
    if (!value) {
        text = @"0";
    }else{
        if ([value isKindOfClass:[NSNumber class]]) {
            text = [value stringValue];
        }else{
            text = value;
        }
    }
    return text;
}


//保存数据的方法
-(BOOL)saveData
{
    NSString *msg = [self validInput];
    if (msg) {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return false;
    }
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSMutableDictionary *dicTmp = modelIns.repairProjects[modelIns.nRowForRepairItemList];
    NSString *chargeDiffVal = self.chargeDiff[self.chargeDiffBtn.titleLabel.text];
    NSString *repairTypeCode = self.repairTypeDic[self.repairTypeBtn.titleLabel.text];
    if (!chargeDiffVal) {
        chargeDiffVal = @"";
    }
    [dicTmp setValue:self.repairNameTxt.text forKey:@"LABOUR_NAME"];
    NSNumber *stdHour = [NSNumber numberWithDouble:[self.standardWorkHourTxt.text doubleValue]];
    [dicTmp setValue:@(self.discount) forKey:@"DISCOUNT"];
    dicTmp[@"REPAIR_TYPE_CODE"] = repairTypeCode;//维修分类
    NSString *oldChargeCode = dicTmp[@"CHARGE_PARTITION_CODE"];
    [dicTmp setValue:chargeDiffVal forKey:@"CHARGE_PARTITION_CODE"];//收费区分
    [dicTmp setValue:stdHour forKey:@"STD_LABOUR_HOUR"];//标准工时
    [dicTmp setValue:@([self.labourPriceBtn.titleLabel.text doubleValue]) forKey:@"LABOUR_PRICE"];//工时单价
    [dicTmp setValue:self.workHourCharge.text forKey:@"LABOUR_AMOUNT"];//工时费
    NSString*itemID=[NSString stringWithFormat:@"%zd",[dicTmp[@"ITEM_ID"] integerValue]];
    if (![itemID isEqualToString:@"0"]) {
        [dicTmp setValue:@"U" forKey:@"STATUS"];
    }else{
        [dicTmp setValue:@"A" forKey:@"STATUS"];
    }
    
    //如果修改的收费区分跟原来的不一样，则与之关联的配件的收费区分也要跟着切换收费区分
    if (![chargeDiffVal isEqualToString:oldChargeCode]) {
        
        [self updateChargeCodeForPart:chargeDiffVal oldCode:oldChargeCode];
        
    }
    return true;
}

-(NSString *)validInput{
    NSString *msg = nil;
    if (self.standardWorkHourTxt.text.length<=0) {
        msg = @"请输入标准工时！";
    }else if (self.labourPriceBtn.currentTitle.length<=0){
        msg = @"请选择工时单价！";
    }else if (self.chargeDiffBtn.titleLabel.text.length<=0){
        msg = @"请选择收费区分";
    }else if (self.repairNameTxt.text.length<=0){
        msg = @"请输入维修项目名称";
    }
    return msg;
}

/** 判断是否是索赔 */
-(BOOL)judgeChargeCode:(NSString *)code{
    if ([code isEqualToString:@"S002"]||[code isEqualToString:@"S004"]||[code isEqualToString:@"S008"]||[code isEqualToString:@"S009"]||[code isEqualToString:@"S010"]) {
        return YES;
    }
    return NO;
}

-(void)updateChargeCodeForPart:(NSString *)newCode oldCode:(NSString *)oldCode{
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSString *itemIds = [self getPartListItemIds:modelIns.partList];//获取与当前维修项目相关的配件列表的id集合
    if (itemIds.length<=0) {
        return;
    }
    BOOL isClaim = [self judgeChargeCode:newCode];
    BOOL isClaim1 = [self judgeChargeCode:oldCode];
    //如果索赔与非索赔切换
    if (isClaim != isClaim1) {
        //查询索赔价和销售价
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"ITEM_ID"] = itemIds;
        [SVProgressHUD showWithStatus:@"请等待...."];
        [MyAFNetWorkManager postWithParam:param andAction:@"QUERY_SALESANDCLAIM_PRICE_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
            [SVProgressHUD dismiss];
            if (error) {
                NSLog(@"查询索赔、销售价格出错");
            }else{
                NSArray *partInfos = obj[@"TM_PART_STOCK_PRICE"];
                [self updatePartList:modelIns.partList partInfos:partInfos isClaim:isClaim newChargeCode:newCode needChangePrice:YES];
            }
            
        }];
    }else{
        
        [self updatePartList:modelIns.partList partInfos:nil isClaim:isClaim newChargeCode:newCode needChangePrice:NO];
    }
    
}

-(void)updatePartList:(NSArray *)partList partInfos:(NSArray *)partInfos isClaim:(BOOL)isClaim newChargeCode:(NSString *)chargeCode needChangePrice:(BOOL)needChangePrice{
    for (NSMutableDictionary *dic in partList) {
        NSString *itemId;
        if ([dic[@"ITEM_ID"] isKindOfClass:[NSString class]]) {
            itemId=dic[@"ITEM_ID"];
        }else{
         itemId= [dic[@"ITEM_ID"] stringValue];
          }
        dic[@"CHARGE_PARTITION_CODE"] = chargeCode;
        dic[@"STATUS"] = @"U";
        if (needChangePrice) {
            double price = [self getPriceWithList:partInfos itemId:itemId isClaim:isClaim];
            dic[@"PART_SALES_PRICE"] = @(price);
            int count = [dic[@"PART_QUANTITY"]integerValue];
            dic[@"PART_SALES_AMOUNT"] = @(price * count);
        }
    }
}

/** 获取与当前维修项目相关的配件列表的id集合 */
-(NSString *)getPartListItemIds:(NSArray *)partList{
    NSMutableString *itemIds = [NSMutableString string];
    NSString *labourCode = self.repairCode.text;
    for (NSDictionary *dic in partList) {
        if ([dic[@"LABOUR_CODE"] isEqualToString:labourCode]) {
            NSString *itemId;
            if ([dic[@"ITEM_ID"] isKindOfClass:[NSString class]]) {
                itemId=dic[@"ITEM_ID"];
             }else{
             itemId= [dic[@"ITEM_ID"] stringValue];
             }
            [itemIds appendString:[NSString stringWithFormat:@"%@,",itemId]];
        }
    }
    if (itemIds.length>0) {
        NSRange range = {0,itemIds.length -1};
        return [itemIds substringWithRange:range];
    }
    return itemIds;
}

/** 获取收费区分对应的价格 */
-(double)getPriceWithList:(NSArray *)partList itemId:(NSString *)itemId isClaim:(BOOL)isClaim{
    double price = 0;
    for (NSDictionary *dic in partList) {
        if ([itemId isEqualToString:[dic[@"ITEM_ID"] stringValue]]) {
            price = isClaim ? [dic[@"CLAIM_PRICE"]doubleValue] : [dic[@"SALES_PRICE"]doubleValue];
        }
    }
    return price;
}

#pragma mark - 键盘托起屏幕的代理方法

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // When the user presses return, take focus away from the text field so that the keyboard is dismissed.
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.superview.frame.size.width, self.view.superview.frame.size.height);
    self.view.superview.frame = rect;
    [UIView commitAnimations];
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    int offset = 150;//键盘高度350
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.superview.frame.size.width;
    float height = self.view.superview.frame.size.height;
    if(offset > 0)
    {
        CGRect rect = CGRectMake(0.0f, -offset,width,height);
        self.view.superview.frame = rect;
    }
    [UIView commitAnimations];
}


-(void)textFieldValueChange:(NSNotification *)note{
    [self computeAmout];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
  if (textField == self.repairNameTxt){
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else  if (self.repairNameTxt.text.length >= 30) {
            self.repairNameTxt.text = [textField.text substringToIndex:30];
            return NO;
            
        }
    }
    return YES;
    
}

-(void)computeAmout{
    double stdHour = [self.standardWorkHourTxt.text doubleValue];
    double price = [self.labourPriceBtn.currentTitle doubleValue];
    self.workHourCharge.text = [NSString stringWithFormat:@"%.2f",stdHour * price];
}

//注册键盘消息
-(void)registerNotificationForKeyBoard
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setViewNormal) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

//视图回归正常状态
-(void)setViewNormal
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.superview.frame.size.width, self.view.superview.frame.size.height);
    self.view.superview.frame = rect;
    [UIView commitAnimations];
}


-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//根据作业区分的ID返回name
-(NSString *)getOperatorNameById:(NSString *)operatorId
{
    //    {"operationTypeId":"14","operationTypeName":"拆装      "},

    for (int i = 0; i<[_arrOriginalDataForOperationType count]; i++)
    {
        NSString *strTmp = [[_arrOriginalDataForOperationType objectAtIndex:i] objectForKey:@"operationTypeId"];
        
        if ([operatorId isEqualToString:strTmp])
        {
            return [[_arrOriginalDataForOperationType objectAtIndex:i] objectForKey:@"operationTypeName"];
        }
    }
    
    return @"";
}

/** 选择收费区分的控制逻辑 */
-(void)labourPriceBtnControl:(NSString *)code{
    //如果收费区分是首保、保修、市场活动、PDI、配件索赔，则工时单价不可修改，工时单价取车辆信息的工时单价
    if ([code isEqualToString:@"S002"]||[code isEqualToString:@"S004"]||[code isEqualToString:@"S008"]||[code isEqualToString:@"S009"]||[code isEqualToString:@"S010"]) {
        [self.labourPriceBtn setTitle:self.labourPrice forState:UIControlStateNormal];
        self.labourPriceBtn.enabled = NO;
    }else{
        
        if (!self.labourPriceBtn.enabled) {
            self.labourPriceBtn.enabled = YES;
            [self.labourPriceBtn setTitle:self.jobSheetLabourPrice forState:UIControlStateNormal];
        }
        
    }
}

#pragma mark - 创建下拉菜单方法

-(void)createThePopViewControl:(UIButton *)sender
{
    if (!contentCon)
    {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
    }
    
    contentCon.delegate = self;
    contentCon.btnSender=sender;
    
    popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [popCon setPopoverContentSize:CGSizeMake(sender.frame.size.width, 280)];
    
    [popCon presentPopoverFromRect:CGRectMake(40, 15, 70, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

//弹出的回调方法
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn
{
    NSString *text = nil;
    if (btn == self.chargeDiffBtn) {
        text = self.chargeDiffKeys[row];
        NSString *code = self.chargeDiff[text];
        [self labourPriceBtnControl:code];
    }else if (btn == self.repairTypeBtn){
        text = self.repairTypeNames[row];
    }else if (btn == self.labourPriceBtn){
        text = self.labourPrices[row];
    }
    [btn setTitle:text forState:UIControlStateNormal];
    
    if (btn == self.labourPriceBtn||self.chargeDiffBtn){
        [self computeAmout];
    }
    //清空数据，退出控件
    [popCon dismissPopoverAnimated:YES];
    popCon = nil;
}

- (IBAction)dropdownBtnTapped:(UIButton *)sender {
    //创建下拉菜单
    [self createThePopViewControl:sender];
    
    if (sender == self.chargeDiffBtn) {
        contentCon.list = self.chargeDiffKeys;
    }else if (sender == self.repairTypeBtn){
        contentCon.list = self.repairTypeNames;
    }else if (sender == self.labourPriceBtn){
        contentCon.list = self.labourPrices;
    }
    //刷新下拉菜单数据
    [contentCon.myTableView reloadData];
}

#pragma mark -懒加载
/** 收费区分 */
-(NSMutableArray *)chargeDiffKeys{
    if (_chargeDiffKeys == nil) {
        _chargeDiffKeys= [NSMutableArray array];
        _chargeDiff = [NSMutableDictionary dictionary];
        _chargeDiffValKey = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_CHARGE_PARTITION"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            if ([name isEqualToString:@"自费"]||[name isEqualToString:@"免费"]||[name isEqualToString:@"保险"]||[name isEqualToString:@"店端活动"]||[name isEqualToString:@"客户活动"]) {
                [_chargeDiffKeys addObject:name];
                [_chargeDiff setObject:val forKey:name];
                [_chargeDiffValKey setObject:name forKey:val];
            }
            
        }
    }
    return _chargeDiffKeys;
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

-(NSMutableArray *)repairTypeNames{
    if (_repairTypeNames == nil) {
        _repairTypeNames= [NSMutableArray array];
        _repairTypeDic = [NSMutableDictionary dictionary];
        _repairTypeCodeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_REPAIR_TYPE_ITEM"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_repairTypeNames addObject:name];
            [_repairTypeDic setObject:val forKey:name];
            [_repairTypeCodeDic setObject:name forKey:val];
        }
    }
    return _repairTypeNames;
}

/** 工时单价 */
-(NSMutableArray *)labourPrices{
    if (_labourPrices == nil) {
        _labourPrices= [NSMutableArray array];
        NSMutableArray *arr = [self readershuDICimform][@"TM_LABOUR_PRICE"];
        for (NSDictionary *dic in arr) {
            NSString *name = [dic[@"NAME"]stringValue];
            //            NSString *val = dic[@"CODE"];
            [_labourPrices addObject:name];
        }
    }
    return _labourPrices;
}
@end
